package steampunk;

import java.util.Hashtable;
import java.util.List;

import steampunk.entities.Entity;
import steampunk.utils.CategoryTable;

public class CollisionEngine {
	
	GameVars vars;
	
	private static CollisionEngine me;
	public static CollisionEngine getInstance() {
		if (me == null)
			me = new CollisionEngine();
		return me;
	}
	private CollisionEngine() {
		this.vars = GameVars.getInstance();
	}
	
	
	private CategoryTable<Entity, Entity> collideTable = new CategoryTable<Entity, Entity>();
	/**
	 * This is the game's collision detection loop.
	 */
	public synchronized void detectCollisions() {
		synchronized (vars.elock) {
			
			collideTable.clear();
			
			List<Entity> dyns = vars.getDynamicEntities();
			List<Entity> all = vars.getSolidEntities();
			
			for (Entity e : dyns)
				e.collisionTestStart();
			
			for (Entity a : dyns) {
				if (a == null || a.shouldRemove())
					continue;
				for (Entity b : all) {
					if (b == null || b.shouldRemove())
						continue;
					if (a == b) continue;
					// Check to see if b has already collided with a
					if (collideTable.contains(b, a))
						continue;
					// Note that a has now collided with b
					collideTable.add(a, b);
					if (a.intersects(b)) {
						// This function is responsible for
						// telling b that I collided with it.
						a.collide(b);
					}
				}
			}
			
			for (Entity e : dyns)
				e.collisionTestEnd();
		}
	}
}
